﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;

using Microsoft.Xna.Framework.Graphics;
using Microsoft.Xna.Framework;

namespace ChouteZemUp.Engine
{
    public class Animation
    {
        private AnimatedGameObject  mOwner;
        private Texture2D mSpriteSheet;
        private Rectangle mBaseRect;
        private int mCurrentFrame;

        private int mNbFrame;
        private float mTimeByFrame;
        private float mTimeSinceStart;

        private float mSpeed;

        private bool mIsUpdated;

        public Animation(AnimatedGameObject pOwner, string pName, string pSpritesheet, float pSpeed, int pNumberOfFrame)
        {
            mIsUpdated = true;

            mOwner = pOwner;

            mNbFrame = pNumberOfFrame;
            mSpeed = pSpeed;

            mTimeByFrame = mSpeed / (float)mNbFrame;

            mSpriteSheet = GameObject.sContent.Load<Texture2D>(pSpritesheet);

            mBaseRect = mOwner.RenderRectangle;
        }

        //---------------------------------------------------------

        public void Update(GameTime pTime)
        {
            if (!mIsUpdated)
                return;

            mTimeSinceStart += (float)(pTime.ElapsedGameTime.TotalSeconds);

            bool lWasChanged = false;
            while (mTimeSinceStart > mTimeByFrame)
            {
                mCurrentFrame++;

                if (mCurrentFrame >= mNbFrame)
                    mCurrentFrame = 0;

                lWasChanged = true;
                mTimeSinceStart -= mTimeByFrame;
            }

            if (lWasChanged)
            {
                mOwner.RenderRectangle = new Rectangle(mCurrentFrame * mBaseRect.Width, 0, mBaseRect.Width, mBaseRect.Height);
            }
        }

        public void Play()
        {
            mTimeSinceStart = 0;
            mCurrentFrame = 0;

            mOwner.Sprite = mSpriteSheet;

            mIsUpdated = true;
        }

        public void Stop()
        {
            mIsUpdated = false;
        }
    }
}
